package com.df.my_net_game.net.websocket;

import com.df.my_net_game.net.base.GTcpIdleHandler;
import com.df.my_net_game.net.base.GTcpServer;
import com.df.my_net_game.net.base.IServerCB;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.List;

public class GwebSocketDefatultChannelInitializer extends ChannelInitializer<SocketChannel> {
    GWebsocketServer server;

    public GwebSocketDefatultChannelInitializer(GWebsocketServer server) {
        this.server = server;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //http编解码器
        pipeline.addLast("http-codec", new HttpServerCodec());
        // 对 httpMessage 进行聚合，聚合成 FullHttpRequest 或 FullHttpResponse
        // 几乎在 netty 编程中, 都会使用该 Handler
        // 支持参数对象解析，比如 POST 参数，设置聚合内容的最大长度
        pipeline.addLast("aggregator", new HttpObjectAggregator(server.getMaxContentLength()));
        //对大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        // 增加心跳支持 start
        // 针对客户端, 如果在 1 分钟之内没有向服务端发送心跳(All),则主动断开
        // 如果是读空闲或者写空闲, 则不处理
        pipeline.addLast(new IdleStateHandler(server.getReaderIdleTimeSecond(), server.getReaderIdleTimeSecond(), server.getAllIdleTimeSecond()));
        // 自定义的空闲状态检测
        pipeline.addLast(new GTcpIdleHandler(server));
        // 支持 WebSocket 数据压缩
        pipeline.addLast(new WebSocketServerCompressionHandler());
        //协议
        pipeline.addLast("protocolHandler", new WebSocketServerProtocolHandler(server.getPath(), null, true));
        IServerCB serverCB = server.getServerCB();
        if(serverCB!=null){
            serverCB.onChannelInit(pipeline,server);
        }
    }
}
